<?php

namespace StudyBuddy\Controllers;

use \StudyBuddy\Responder;
use \StudyBuddy\QuestionParser;
use \StudyBuddy\SubmittedQuestionWWW;

/**
 * This controller processes the
 * form values of the Ask form
 *
 */
class Ask extends Askform
{

	protected $membersOnly = true;


	protected function main(){
		$this->aPageVars['title'] = $this->_('Ask a question');

		$a = $this->oRegistry->Request->getArray();
		d('request: '.print_r($a, 1).' POST: '.print_r($_POST, 1));

		$this->makeForm();

		if($this->oForm->validate()){
			$this->process();
		} else {
			$this->showFormWithErrors();
		}
	}


	protected function showFormWithErrors(){
		$this->makeTopTabs()
		->makeMemo()
		->setForm();
	}


	/**
	 *
	 * Process submitted form values
	 */
	protected function process(){

		$formVals = $this->oForm->getSubmittedValues();
		d('formVals: '.print_r($formVals, 1));
		$oAdapter = new QuestionParser($this->oRegistry);
		try{
			$oQuestion = $oAdapter->parse(new SubmittedQuestionWWW($this->oRegistry, $formVals));
			d('cp created new question');
			d('title: '.$oQuestion['title']);
			
			Responder::redirectToPage($oQuestion->getUrl());
		} catch (QuestionParserException $e){
			$this->oForm->setFormError($e->getMessage());
			$this->showFormWithErrors();
		}
	}

}
